package com.lwj.springbootvue.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lwj.springbootvue.constants.HttpStatus;
import com.lwj.springbootvue.exception.ServiceException;
import com.lwj.springbootvue.model.User;
import com.lwj.springbootvue.model.dto.LoginDto;
import com.lwj.springbootvue.response.Result;
import com.lwj.springbootvue.service.UserService;
import com.lwj.springbootvue.util.JwtUtils;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;




/*
* 登录认证
* */
@RestController
@RequestMapping("/user")
public class loginController {

    @Autowired
    private UserService userService;

    private final PasswordEncoder passwordEncoder;

    public loginController(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }




    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto){
        String token = userService.login(loginDto);

        if(ObjectUtil.isNotNull(token)){
            // token 信息存储进入JSON返回 前端
            return Result.success("登录成功！").put("token",token);
        }else{
            throw new ServiceException(HttpStatus.FORBIDDEN,"登录失败！");
        }
    }


    @PostMapping("/register")
    public Result register(@RequestBody LoginDto loginDto){
        System.out.println(loginDto);
        boolean register = userService.register(loginDto);

        if(register){
            return Result.success("注册成功！");
        }
        return Result.error("注册失败！");
    }

    @GetMapping("/admin")
    public Result getAdmin(HttpServletRequest httpServletRequest){
        // 根据token获取用户数据并解析，放回前端
        String token=httpServletRequest.getHeader("king-Authorization");
        User tokenUser = JwtUtils.getTokenUser(token);
        return Result.success(tokenUser);
    }


    @PostMapping("/changePassword")
    public Result changeAdminPassword(@RequestBody String  newPassword,HttpServletRequest httpServletRequest){
        // 根据token获取用户数据并解析 当前登录的用户信息
        String token=httpServletRequest.getHeader("king-Authorization");
        User tokenUser = JwtUtils.getTokenUser(token);
        // 更新密码
        userService.changeAdminPassword(newPassword.replaceAll("=",""),tokenUser);
        return Result.success();
    }



    @GetMapping("/test")
    public String test(HttpServletRequest httpServletRequest){
        System.out.println(httpServletRequest.getHeader("king-Authorization"));
        return "test";
    }

    @GetMapping("/error")
    public String error(){
        throw new ServiceException("测试接口",HttpStatus.BAD_REQUEST);
    }


}
